﻿using Max.PH5_2006.ShoppingSite.Domain;
using Max.PH5_2006.ShoppingSite.DTO;
using Max.PH5_2006.ShoppingSite.IService;
using Max.PH5_2006.ShoppingSite.Service;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace Max.PH5_2006.ShoppingSite.API.Controllers
{
    [Route("category")]
    [ApiController]
    public class CategoryController : ControllerBase
    {

        ICategoryService _service;

        public CategoryController(ICategoryService service)
        {
            _service = service;
        }


        [HttpGet]
        public IActionResult GetAll()
        {
            ResponseResultDto response = new();
            var data = _service.Query();
            var result = this.GetCategory(data, new Guid().ToString());//"00000000-0000-0000-0000-000000000000");
            response.Data = result;
            return Ok(response);
        }

        [HttpPost]
        public IActionResult Add(CategoryEntity entity)
        {
            ResponseResultDto response = new();


            _service.Add(entity);

            return Ok(response);
        }


        private List<dynamic> GetCategory(List<CategoryEntity> source, string id)
        {
            var list = source.Where(x => id.Equals(x.PId.ToString())).ToList();

            List<dynamic> data = new List<dynamic>();

            foreach (var item in list)
            {
                var d = GetCategory(source, item.Id.ToString());
                data.Add(new
                {
                    item.Name,
                    item.Id,
                    item.Image,
                    children = (d == null || d.Count <= 0) ? null : d
                });
            }
            return data;
        }


    }
}
